package com.zsl.controller.Login;

import com.alibaba.fastjson.JSON;
import com.zsl.model.Users;
import com.zsl.service.OrderItemService;
import com.zsl.service.UsersService;
import com.zsl.service.impl.OrderItemServiceImpl;
import com.zsl.service.impl.UsersServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "LoginController", urlPatterns = "/login")
public class LoginController extends HttpServlet {

    private UsersService usersService=new UsersServiceImpl();
    private Users user=null;
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        Map<String,Object> res = new HashMap<>();

        String uname=request.getParameter("uname");
        String pwd=request.getParameter("pwd");
        //空值
        if (uname.equals("")||pwd.equals("")) {
            res.put("code", "0");
            res.put("msg","输入出错");
            out.write(JSON.toJSONString(res));
        }
        else{
            try {
                //判断用户是否存在
                if(usersService.isRealUser(uname,pwd)){
                    res.put("code","1");
                    res.put("msg","登陆成功");
                    //TODO 由于没有设置角色表，默认用户名为admin的角色为admin
                    HttpSession session = request.getSession();
                    if(uname.equals("admin")){
                        session.setAttribute("role","admin");
                        res.put("role","admin");
                    }else {
                        session.setAttribute("role","users");
                        res.put("role","users");
                    }
                    //通过用户名获取角色的id
                    String id=usersService.getIdByName(uname);
                    session.setAttribute("id",id);
                }
                else{
                    res.put("code","0");
                    res.put("msg","登录失败");
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }finally {
                out.write(JSON.toJSONString(res));
            }
        }
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
